/*
 * @Description: Admin Controller
 * @Author: Jinzhu Liu
 * @Date: 2021-12-17 15:43:06
 * @LastEditor: Jinzhu Liu
 * @LastEditTime: 2021-12-26 23:52:33
 */

import { Context } from "koa";
import AdminService from "../service/admin_service";
import paginate from "../../utils/pagination";
import response from "../../utils/response";
import { Rules } from "async-validator";
import validate from "../../utils/validate";
import { createHash } from "crypto";

interface IAdmin{
    id: number
    name: string
    password: string
}

class AdminController {
    async getAdminList(ctx: Context) {
        const usp = new URLSearchParams(ctx.querystring)
        let page = 1, limit = 10
        if (usp.get('page') !== null) {
            let pageParam = Number(usp.get('page'))
            if (!isNaN(pageParam)) {
                page = pageParam
            }
        }
        if (usp.get('limit') !== null) {
            let limitParam = Number(usp.get('limit'))
            if (!isNaN(limitParam)) {
                limit = limitParam
            }
        }
        const { rows, count } = await AdminService.getAdminListByPage(page, limit)
        response.success(ctx, paginate(rows, page, count, limit))
    }

    async addAdmin(ctx: Context) {
        const rules: Rules = {
            name: [
                {
                    type: 'string',
                    required: true,
                    message: 'Name cannot be null'
                }
            ],
            password: [
                {
                    type: 'string',
                    required: true,
                    message: 'Password cannot be null'
                },
                {
                    type: 'string',
                    min: 6,
                    message: 'Password length cannot less than 6 charactors'
                }
            ]
        }

        const {data, error} = await validate<IAdmin>(ctx, rules)
        if (error !== null) {
            return response.error(ctx, error)
        }

        if (data !== null) {
            const admin = await AdminService.getAdminByName(data.name)
            if (admin !== null) {
                return response.error(ctx, 'Admin is already exist')
            }

            data.password = createHash('md5').update(data.password).digest('hex')
            const row = await AdminService.addAdmin(data)
            if (row.id > 0) {
                return response.success(ctx)
            } else {
                return response.error(ctx, 'Insert failed')
            }
        } else {
            return response.error(ctx, 'Admin data cannot be null')
        }
    }

    async updateAdmin(ctx: Context) {
        const id = ctx.params['id'] as number
        const admin = await AdminService.getAdminById(id)
        if (admin === null) {
            return response.error(ctx, 'Admin not exist')
        }
        const rules: Rules = {
            name: [
                {
                    type: 'string',
                    required: true,
                    message: 'Name cannot be null'
                }
            ]
        }
        const {data, error} = await validate<IAdmin>(ctx, rules)
        if (error !== null) {
            return response.error(ctx, error)
        }
        if (data) {
            if (data.password != undefined && data.password != '') {
                data.password = createHash('md5').update(data.password).digest('hex')
            }
            const [number] = await AdminService.updateAdmin(id, data)
            if (number > 0) {
                return response.success(ctx)
            } else {
                return response.error(ctx, 'Update Admin failed')
            }
        } else {
            return response.error(ctx, 'Admin data cannot be null')
        }
    }
    /**
     * @description: Delete admin user
     * @param {Context} ctx
     * @return {*}
     */
    async deleteAdmin(ctx: Context) {
        const id = ctx.params['id'] as number
        const admin = await AdminService.getAdminById(id)
        if (admin === null) {
            return response.error(ctx, 'Admin not exist')
        }
        const row = await AdminService.deleteAdmin(id)
        if (row > 0) {
            return response.success(ctx)
        } else {
            return response.error(ctx, 'Delete Admin failed')
        }
    }
}

export default new AdminController